package 力扣面试经典150;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2024-03-03
 * Time:17:19
 */

/**
 * 力扣面试经典150:14. 最长公共前缀
 * 简单
 * 相关标签
 * 相关企业
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * 如果不存在公共前缀，返回空字符串 ""。
 * 示例 1：
 * 输入：strs = ["flower","flow","flight"]
 * 输出："fl"
 */
public class longestCommonPrefix {
    public static void main(String[] args) {
        longestCommonPrefix(new String[]{"flower","flow","flight"});
    }
    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }

        String word = strs[0];
        int length = word.length();
        StringBuilder ans = new StringBuilder();

        for (int i = 0; i < length; i++) {
            char c = word.charAt(i);
            for (int j = 1; j < strs.length; j++) {
                if (i >= strs[j].length() || strs[j].charAt(i) != c) {
                    return ans.toString();
                }
            }
            ans.append(c);
        }

        return ans.toString();
    }
}
